package org.lql.algo.codecrush.week008;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author: liangqinglong
 * @date: 2025-08-19 00:03
 * @description: 349. 两个数组的交集 <a href="https://leetcode.cn/problems/intersection-of-two-arrays/description/">...</a>
 **/
public class Intersection {

	public int[] intersection(int[] nums1, int[] nums2) {
		// 存储 nums1 中的所有元素
		Set<Integer> set = new HashSet<>();
		for (int num : nums1) {
			set.add(num);
		}

		// 存储交集结果
		Set<Integer> resSet = new HashSet<>();
		for (int num : nums2) {
			if (set.contains(num)) {
				resSet.add(num);
			}
		}

		// 转换成数组
		int[] res = new int[resSet.size()];
		int i = 0;
		for (int num : resSet) {
			res[i++] = num;
		}
		return res;
	}

	public static void main(String[] args) {
		Intersection intersection = new Intersection();
		int[] nums1 = new int[]{1, 2, 2, 1};
		int[] nums2 = new int[]{2, 2};
		int[] intersection1 = intersection.intersection(nums1, nums2);
		System.out.println(Arrays.toString(intersection1));
		nums1 = new int[]{4, 9, 5};
		nums2 = new int[]{9, 4, 9, 8, 4};
		int[] intersection2 = intersection.intersection(nums1, nums2);
		System.out.println(Arrays.toString(intersection2));
	}

}
